package com.x.erp.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.x.erp.model.*;
import com.x.erp.payload.CarStateMsg;
import com.x.erp.rpc.*;
import com.x.erp.util.ConstantState;
import com.x.erp.util.ConstantTopic;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.rocketmq.RocketMqProducer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 车辆信息
 */
@RestController
public class CarController extends BaseController{

	@Reference
	private CarRpcService carRpcService;//车辆信息服务

	@Reference
	private ModelRpcService modelRpcService;//车型服务

	@Reference
	private DetectionRpcService detectionRpcService;//检测单信息服务
	
	@Reference
	private CarAuthRpcService carAuthRpcService;//车辆认证服务

	@Reference
	private CarLocationRpcService carLocationRpcService;//车牌所在地信息服务

	@Reference
	private CarOrderRpcService carOrderRpcService;//车辆预订服务

	@Reference
	private CarSelectTemplateRpcService carSelectTemplateRpcService;//车辆查询模板订阅服务

	@Reference
	private CarImageRpcService carImageRpcService;//图片服务

	@Autowired
	private FastFileStorageClient fdfsClient;//文件服务

	@Autowired
	private RocketMqProducer rocketMqProducer;

	/**
	 * 查询车辆信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = {"/getCarList", "/car/getCarList"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getCarList(Car car) {
		if(StringUtils.isEmpty(car.getMarketId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "marketId不能为空！");
		}
		if(car.getPageIndex() == null){
			car.setPageIndex(1);
		}
		if(car.getPageSize() == null){
			car.setPageSize(15);
		}
		List<Car> cars = carRpcService.selectCarList(car);
		if(cars != null && !cars.isEmpty()){
			for (Car carInfo : cars){
				if(carInfo.getCarPledgeState() != null && carInfo.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED
						&& carInfo.getCarSiteState() != null && carInfo.getCarSiteState() == ConstantState.CAR_SITE_STATE_OUT_FINISH){
					if(carInfo.getCarSiteTime() != null) {
						if ((System.currentTimeMillis() - carInfo.getCarSiteTime().getTime()) / (1000 * 60) > 300) {
							carInfo.setCarSiteStatus(1);
						}
					}
				}
			}
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", cars);
	}

	@RequestMapping(value = {"/getCarStatisList", "/car/getCarStatisList"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getCarStatisList(Car car, @DateTimeFormat(pattern="yyyy-MM-dd")Date startDate,
										@DateTimeFormat(pattern="yyyy-MM-dd")Date endDate, Integer statisType) {
		if(startDate == null || endDate ==null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "查询日期不能为空！");
		}
		if(statisType == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "统计类型不能为空！");
		}
		switch (statisType) {
			case 1:
				//入库量
				return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", carRpcService.selectCarStorageList(car, startDate, endDate));
			case 2:
				//出库量
				return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", carRpcService.selectCarOutStockList(car, startDate, endDate));
			case 3:
				//本月库存量
				car.setCarStockState(ConstantState.CAR_STOCK_STATE_OUT_ING); // 
				return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", carRpcService.selectCarStorageList(car, startDate, endDate));
			case 4:
				//当前在库
				car.setCarStockState(ConstantState.CAR_STOCK_STATE_OUT_ING);
				return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", carRpcService.selectCarStorageList(car, null, null));
			case 5:
				//预订
				return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", carRpcService.selectCarOrderList(car, startDate, endDate));
			default:
				return new ResultModel(ResultCode.RESULT_FAIL, "统计类型错误！");
		}
	}


	/**
	 * 根据条件查询车辆数量
	 * @param car
	 * @return
	 */
	@RequestMapping(value = {"/getCarNum", "/car/getCarNum"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getCarNum(Car car) {
		if(StringUtils.isEmpty(car.getMarketId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "marketId不能为空！");
		}
		Map<String, Object> res = new HashMap<>();
		res.put("total", carRpcService.selectCarNum(car));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}

	/**
	 * 获取工作台车辆数量
	 * @param car
	 * @return
	 */
	@RequestMapping(value = "/car/getCarNumInfo", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getCarNumInfo(Car car) {
		if(StringUtils.isEmpty(car.getMarketId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "marketId不能为空！");
		}
		Map<String, Object> res = new HashMap<>();
		car.setCarStockState(ConstantState.CAR_STOCK_STATE_INITIAL);
		res.put("initialNum", carRpcService.selectCarNum(car));
		car.setCarStockState(ConstantState.CAR_STOCK_STATE_IN_ING);
		res.put("toStorageApplyNum", carRpcService.selectCarNum(car));
		car.setCarStockState(ConstantState.CAR_STOCK_STATE_IN_FINISH);
		res.put("storageNum", carRpcService.selectCarNum(car));
		car.setCarStockState(ConstantState.CAR_STOCK_STATE_OUT_FINISH);
		res.put("outStorageNum", carRpcService.selectCarNum(car));
		car.setCarStockState(null);
		car.setCarOrderState(ConstantState.CAR_ORDER_STATE_ORDERED);
		res.put("carOrderNum", carRpcService.selectCarNum(car));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}

	/**
	 * 根据ID查询车辆信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = {"/getCarById", "/car/getCarById"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getCarById(String carId, Integer imageViewId) {
		Car car = new Car();
		if(StringUtils.isEmpty(carId)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		car.setCarId(carId);
		car = carRpcService.selectCar(car);
		if(car != null) {
			Model model = new Model();
			model.setModelId(car.getModelId());
			List<Model> models = modelRpcService.selectModelList(model);
			if(models != null && models.size() > 0){
				model = models.get(0);
			}
			car.setModel(model);
			car.getModelId();
			CarImage carImage = new CarImage();
			carImage.setCarId(carId);
			if(StringUtils.isNotEmpty(car.getCarPlate())) {
				List<CarLocation> carLocations = carLocationRpcService.selectCarLocationList(new CarLocation());
				for(CarLocation carLocation : carLocations) {
					if(car.getCarPlate().toUpperCase().startsWith(carLocation.getLocationCode())) {
						car.setCarLocationCityName(carLocation.getLocationCityName());
						break;
					}
				}
			}
			List<CarImage> carImages = carImageRpcService.selectCarImageList(carImage, imageViewId);
			car.setCarImages(carImages);
			Car serchCar = new Car();
			serchCar.setCarId(carId);
			Map<String,Object> carRadarInfo = carRpcService.selectCarRadarInfo(new Car(carId),null,null,null);
			car.setCarRadarInfo(carRadarInfo);
			return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", car);
		}
		return new ResultModel(ResultCode.RESULT_FAIL, "查询失败");
	}

	/**
	 * 上传车辆图片
	 * @param carId
	 * @param imageKey
	 * @param uploadFile
	 * @return
	 */
	@RequestMapping(value = {"/uploadCarImage", "/car/uploadCarImage"}, method = {RequestMethod.POST})
	public ResultModel uploadCarImage(String carId, String imageKey,
									  @RequestParam(value = "uploadFile", required = true) CommonsMultipartFile uploadFile) {
		if (uploadFile == null || uploadFile.isEmpty()) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上传文件不能为空");
		}
		String pathUrl = "";
		//上传图片
		String fileName = uploadFile.getOriginalFilename();
		try {
			pathUrl = fdfsClient.uploadFile(uploadFile.getInputStream(), fdfsClient.getFileExt(fileName));
		} catch (IOException e) {
			e.printStackTrace();
			return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
		}
		if(pathUrl == null || pathUrl.equalsIgnoreCase("null")) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
		}
		Map<String, Object> res = new HashMap<>();
		res.put("pathUrl", pathUrl);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "上传成功", res);
	}

	/**
	 * 新增车辆信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = {"/insertCar", "/car/insertCar"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertCar(Car car, String carImageJson, String carValuationJson, HttpServletRequest request) {
		String source = request.getHeader("source");
		if(car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆信息不能为空！");
		}
		if(car.getCarTypeId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆类型不能为空！");
		}
		if(car.getBrandId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "品牌不能为空！");
		}
		if(car.getSeriesId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车系不能为空！");
		}
		if(car.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型不能为空！");
		}
		if(StringUtils.isEmpty(car.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场不能为空！");
		}
		if(StringUtils.isEmpty(car.getShopId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "店铺不能为空！");
		}
		if(StringUtils.isEmpty(car.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID不能为空！");
		}
		if(!valiCarVin(car.getCarVin())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号信息不正确（17位）！");
		}
		if(car.getCarMileage() == null || car.getCarMileage().compareTo(new BigDecimal(0.0001)) < 0 || car.getCarMileage().compareTo(new BigDecimal(100)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "行驶里程数据错误（大于0小于100/万公里）！");
		}
		if(StringUtils.isEmpty(car.getCarOutColor())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车身颜色不能为空！");
		}
		if(car.getCarLicenceDate() != null && car.getCarLicenceDate().after(this.getDate(0))){
			return new ResultModel(ResultCode.RESULT_FAIL, "首次上牌日期不能大于当前日期！");
		}
		if(!valiCarVinExist(car.getCarVin(), car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号已存在！");
		}
		Date cDate = this.getDate(0);
		if(car.getCarLicenceDate() == null){
			car.setCarLicenceDate(cDate);
		}
		car.setCarVin6(car.getCarVin().substring(11, 17));//截取后6位
		//初始化状态值
		car.setCarAuthState(ConstantState.CAR_AUTH_STATE_INITIAL);
		car.setCarSaleState(ConstantState.CAR_SALE_STATE_INITIAL);
		car.setCarStockState(ConstantState.CAR_STOCK_STATE_INITIAL);
		car.setCarDetectState(ConstantState.CAR_DETECT_STATE_INITIAL);
		car.setCarOrderState(ConstantState.CAR_ORDER_STATE_INITIAL);
		car.setCarSiteState(ConstantState.CAR_SITE_STATE_INITIAL);
		car.setCarPledgeState(ConstantState.CAR_PLEDG_STATE_INITIAL);
		List<CarImage> images = JSON.parseArray(carImageJson, CarImage.class);
		//判断首图是否为空
		if(images != null && !valiCarImage(images, car)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "首图不能为空！");
		}
		car.setCarImages(images);
		car.setCarCreateTime(cDate);
		car.setCarSiteTime(cDate);
		//获取估值信息
		if (StringUtils.isNotBlank(carValuationJson)){
			List<CarValuation> carValuations = JSON.parseArray(carValuationJson, CarValuation.class);
			car.setCarValuations(carValuations);
		}
		//记录日志信息
		CarLog carLog = new CarLog("录入车辆信息", cDate, car.getUserId(), null);
		carLog.setCarStateKey("carStockState");
		carLog.setCarStateValue(ConstantState.CAR_STOCK_STATE_INITIAL);
		carLog.setCarLogSource(source);
		List<CarLog> carLogs = new ArrayList<>();
		carLogs.add(carLog);
		car.setCarLogs(carLogs);
		car = carRpcService.insertCar(car);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功", car);
	}

	/**
	 * 修改车辆信息
	 * @param car
	 * @return
	 */
	@RequestMapping(value = {"/car/updateCar"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updateCar(Car car, String carImageJson, String carValuationJson) {
		if(car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆信息不能为空！");
		}
		if(StringUtils.isEmpty(car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(car.getCarLicenceDate() != null && car.getCarLicenceDate().after(this.getDate(0))) {
			return new ResultModel(ResultCode.RESULT_FAIL, "首次上牌日期不能大于当前日期！");
		}
		if(StringUtils.isNotEmpty(car.getCarVin()) && !valiCarVinExist(car.getCarVin(), car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号已存在！");
		}
		if(car.getCarMileage() != null && (car.getCarMileage().compareTo(new BigDecimal(0.0001)) < 0 || car.getCarMileage().compareTo(new BigDecimal(100)) >= 0)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "行驶里程数据错误（大于0小于100/万公里）！");
		}
		if(car.getCarRetailPrice() != null && (car.getCarRetailPrice().compareTo(new BigDecimal(0)) < 0 || car.getCarRetailPrice().compareTo(new BigDecimal(10000)) >= 0)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的零售价（0~9999.99/万元）！");
		}
		car.setMarketId(null);
		car.setShopId(null);
		car.setUserId(null);
		List<CarImage> images = JSON.parseArray(carImageJson, CarImage.class);
		//判断首图是否为空
		if(images != null && !valiCarImage(images, car)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "首图不能为空！");
		}
		car.setCarImages(images);
		//获取估值信息
		if (StringUtils.isNotBlank(carValuationJson)){
			List<CarValuation> carValuations = JSON.parseArray(carValuationJson, CarValuation.class);
			car.setCarValuations(carValuations);
		}
		carRpcService.updateCarInfo(car);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！", car);
	}

	/**
	 * 车辆上架申请  车场区域、品牌车系、宣传标题、车架号、行驶里程、是否已上牌、首次上牌年月、年审日期、交强险日期、外观颜色、变速箱、排量、零售价格
	 * @param car
	 * @param carImageJson
	 * @return
	 */
	@RequestMapping(value = "/car/putOnSale", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel putOnSale(Car car, String carImageJson, HttpServletRequest request) {
		String source = request.getHeader("source");
		if(car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆信息不能为空！");
		}
		if(StringUtils.isEmpty(car.getUserId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID不能为空！");
		}
		if(StringUtils.isEmpty(car.getSaleUserId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "销售用户不能为空！");
		}
		if(StringUtils.isEmpty(car.getRegionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车场区域不能为空！");
		}
		if(car.getBrandId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "品牌不能为空！");
		}
		if(car.getSeriesId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车系不能为空！");
		}
		if(car.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型不能为空！");
		}
		if(StringUtils.isEmpty(car.getCarTitle())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "宣传标题不能为空！");
		}
		if(!valiCarVin(car.getCarVin())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号信息不正确（17位）！");
		}
		if(!valiCarVinExist(car.getCarVin(), car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号已存在！");
		}
		if(StringUtils.isEmpty(car.getCarOutColor())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车身颜色不能为空！");
		}
		if(car.getCarMileage() == null || car.getCarMileage().compareTo(new BigDecimal(0.0001)) < 0 || car.getCarMileage().compareTo(new BigDecimal(100)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "行驶里程数据错误（大于0小于100/万公里）！");
		}
		if(car.getCarRetailPrice() == null || car.getCarRetailPrice().compareTo(new BigDecimal(0)) < 0 || car.getCarRetailPrice().compareTo(new BigDecimal(10000)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的零售价（0~9999.99/万元）！");
		}
		if(car.getCarLicenceState() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择是否上牌");
		}
		//是否上牌（1：已上牌、2：未上牌、3：新车）
		if(car.getCarLicenceState() == 1 && car.getCarLicenceDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写上牌日期");
		}else if(car.getCarLicenceDate() != null && car.getCarLicenceDate().after(this.getDate(0))){
			return new ResultModel(ResultCode.RESULT_FAIL, "首次上牌日期不能大于当前日期！");
		}
		if(car.getCarLicenceState() == 1 && car.getCarValidateDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写年审日期");
		}
		if(car.getCarLicenceState() == 1 && car.getCarForceInsuranceDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写交强险日期");
		}
		if(StringUtils.isEmpty(car.getCarGearbox())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择变速箱");
		}
		/*if(car.getCarTransferNum() == null || car.getCarTransferNum() < 0 || car.getCarTransferNum() > 99){
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的过户次数（0~99）");
		}*/
		if(StringUtils.isEmpty(car.getCarDisplacement())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择排量");
		}
		List<CarImage> images = JSON.parseArray(carImageJson, CarImage.class);
		if(images == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "图片信息不能为空！");
		}
		// 验证图片正确性
		if(!valiCarImage(images, car)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "首图不能为空！");
		}
		/*if(images == null || images.size() < 10){
			return new ResultModel(ResultCode.RESULT_FAIL, "图片不足（车辆图片10张）");
		}*/
		car.setCarImages(images);
		car.setCarSaleState(ConstantState.CAR_SALE_STATE_ONSALE_ING);
		car.setCarSaleTime(this.getDate(0));
		// 记录车辆日志
		CarLog carLog = new CarLog("车辆申请上架", new Date(), car.getUserId(), car.getCarId());
		carLog.setCarStateKey("carSaleState");
		carLog.setCarStateValue(ConstantState.CAR_SALE_STATE_ONSALE_ING);
		carLog.setCarLogSource(source);
		List<CarLog> carLogs = new ArrayList<>();
		carLogs.add(carLog);
		car.setCarLogs(carLogs);
		car.setMarketId(null);
		car.setShopId(null);
		car.setUserId(null);
		carRpcService.updateCarInfo(car);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "车辆申请成功！");
	}

	/**
	 * 车辆入库申请  车场区域、品牌车系、宣传标题、车架号、行驶里程、是否已上牌、首次上牌年月、年审日期、交强险日期、外观颜色、变速箱、排量、零售价格
	 * @param car
	 * @param carImageJson
	 * @return
	 */
	@RequestMapping(value = "/car/toStorage", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel toStorage(Car car, String carImageJson, String carValuationJson, HttpServletRequest request) {
		String resource = request.getHeader("resource");
		if(car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆信息不能为空！");
		}
		if(StringUtils.isEmpty(car.getUserId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID不能为空！");
		}
		if(StringUtils.isEmpty(car.getSaleUserId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "销售用户不能为空！");
		}
		if(StringUtils.isEmpty(car.getRegionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车场区域不能为空！");
		}
		if(car.getBrandId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "品牌不能为空！");
		}
		if(car.getSeriesId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车系不能为空！");
		}
		if(car.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型不能为空！");
		}
		if(StringUtils.isEmpty(car.getCarTitle())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "宣传标题不能为空！");
		}
		if(!valiCarVin(car.getCarVin())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号信息不正确（17位）！");
		}
		if(!valiCarVinExist(car.getCarVin(), car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号已存在！");
		}
		if(StringUtils.isEmpty(car.getCarOutColor())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车身颜色不能为空！");
		}
		if(car.getCarMileage() == null || car.getCarMileage().compareTo(new BigDecimal(0.0001)) < 0 || car.getCarMileage().compareTo(new BigDecimal(100)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "行驶里程数据错误（大于0小于100/万公里）！");
		}
		if(car.getCarRetailPrice() == null || car.getCarRetailPrice().compareTo(new BigDecimal(0)) < 0 || car.getCarRetailPrice().compareTo(new BigDecimal(10000)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的零售价（0~9999.99/万元）！");
		}
		if(car.getCarLicenceState() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择是否上牌");
		}
		//是否上牌（1：已上牌、2：未上牌、3：新车）
		if(car.getCarLicenceState() == 1 && car.getCarLicenceDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写上牌日期");
		}else if(car.getCarLicenceDate() != null && car.getCarLicenceDate().after(this.getDate(0))){
			return new ResultModel(ResultCode.RESULT_FAIL, "首次上牌日期不能大于当前日期！");
		}
		if(car.getCarLicenceState() == 1 && car.getCarValidateDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写年审日期");
		}
		if(car.getCarLicenceState() == 1 && car.getCarForceInsuranceDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写交强险日期");
		}
		if(StringUtils.isEmpty(car.getCarGearbox())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择变速箱");
		}
		Integer carStockState = car.getCarStockState();
		// 如果没传库存状态就设为10，申请入库
		if(carStockState == null){
			carStockState = ConstantState.CAR_STOCK_STATE_IN_ING;
			car.setCarStockState(carStockState);
		}
		/*if(car.getCarTransferNum() == null || car.getCarTransferNum() < 0 || car.getCarTransferNum() > 99){
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的过户次数（0~99）");
		}*/
		if(StringUtils.isEmpty(car.getCarDisplacement())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择排量");
		}
		List<CarImage> images = JSON.parseArray(carImageJson, CarImage.class);
		if(images == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "图片信息不能为空！");
		}
		// 验证图片正确性
		if(!valiCarImage(images, car)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "首图不能为空！");
		}
		car.setCarImages(images);
		//获取估值信息
		if (StringUtils.isNotBlank(carValuationJson)){
			List<CarValuation> carValuations = JSON.parseArray(carValuationJson, CarValuation.class);
			car.setCarValuations(carValuations);
		}
		car.setCarStockTime(this.getDate(0));
		// 记录车辆日志
		CarLog carLog = new CarLog(null, new Date(), car.getUserId(), car.getCarId());
		carLog.setCarLogInfo(ConstantState.getCarStockStateMsg(carStockState));
		carLog.setCarStateKey("carStockState");
		carLog.setCarStateValue(carStockState);
		carLog.setCarLogSource(resource);
		List<CarLog> carLogs = new ArrayList<>();
		carLogs.add(carLog);
		car.setCarLogs(carLogs);
		car.setMarketId(null);
		car.setUserId(null);
		carRpcService.updateCarState (car);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "车辆申请入库成功！");
	}

	/**
	 * 验证车辆vin码
	 * @param vin
	 * @return
	 */
	private boolean valiCarVin(String vin){
		if(StringUtils.isEmpty(vin) || vin.length() != 17){
			return false;
		}
		String vinStr = vin.toUpperCase();
		if(vinStr.contains("I") || vinStr.contains("O") || vinStr.contains("Q")) {
			return false;
		}
		return true;
	}

	/**
	 * 验证车架号是否存在
	 * @param vin
	 * @param carId
	 * @return
	 */
	private boolean valiCarVinExist(String vin, String carId){
		Car car = new Car();
		car.setCarVin(vin);
		//根据Vin查询车辆信息
		List<Car> cars = carRpcService.selectValiCarVin(car);
		if(cars != null && cars.size() > 0){
			if(StringUtils.isEmpty(carId)){
				// 新增车辆时vin码已存在
				return false;
			}else{
				for(Car carInfo:cars){
					if(carInfo.getCarId().equals(carId)){
						// 修改车辆时如果修改的是相同车辆返回true
						return true;
					}
				}
				return false;
			}
		}
		return true;
	}

	/**
	 * 验证图片正确性
	 * @param images
	 * @return
	 */
	private boolean valiCarImage(List<CarImage> images, Car car) {
		Map<String, CarImage> imageMap = new HashMap<>();
		boolean ok = false;
		for(CarImage cImage : images) {
			// 过滤url为空字符串的image
			if(StringUtils.isEmpty(cImage.getImageUrl())) {
				continue;
			}
			// 过滤重复Key
			if(imageMap.get(cImage.getImageKey()) != null) {
				continue;
			}
			imageMap.put(cImage.getImageKey(), cImage);
			if(!ok && cImage.getImageKey().equalsIgnoreCase("left_anterior") && StringUtils.isNotEmpty(cImage.getImageUrl())) {
				car.setCarImageUrl(cImage.getImageUrl());
				ok = true;
			}
		}
		// 清空当前list
		images.clear();
		// 过滤后的数据重新放到list中
		for(String key : imageMap.keySet()){
			images.add((imageMap.get(key)));
		}
		return ok;
	}

	/**
	 * 修改车辆状态
	 * @param stateKey
	 * @param stateValue
	 * @return
	 */
	@RequestMapping(value = {"/car/updateCarState"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updateCarState(Car carInfo, String stateKey, Integer stateValue, String content, HttpServletRequest request) {
		String source = request.getHeader("source");
		if(carInfo == null || StringUtils.isEmpty(carInfo.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(StringUtils.isEmpty(carInfo.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "操作人ID不能为空！");
		}
		if(StringUtils.isEmpty(stateKey)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "状态KEY不能为空！");
		}
		if(stateValue == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "状态值不能为空！");
		}
		if(content != null && content.length() > 100){
			return new ResultModel(ResultCode.RESULT_FAIL, "审核不通过原因字数不能超过100！");
		}
		//car对象封装更新条件
		Car car = new Car();
		car.setCarId(carInfo.getCarId());
		//selectCar根据carID查询出来的车辆信息
		Car selectCar = carRpcService.selectCar(car);
		CarLog carLog = new CarLog(new Date(), carInfo.getUserId(), carInfo.getCarId(), stateKey, stateValue);
		carLog.setCarLogSource(source);
		List<CarLog> carLogs = new ArrayList<>();
		switch (stateKey) {
			case "carAuthState":
				//认证状态 0 未认证 10 已认证
				car.setCarAuthState(stateValue);
				carLog.setCarLogInfo((stateValue == ConstantState.CAR_AUTH_STATE_AUTHED?"车辆认证":"未知"));
				if(stateValue == ConstantState.CAR_AUTH_STATE_AUTHED){
					//申请认证
					//记录操作日志
					carLogs.add(carLog);
					car.setCarLogs(carLogs);
					//创建车辆认证信息
					if(!createCarAuth(carInfo, car, selectCar)){
						return new ResultModel(ResultCode.RESULT_FAIL, "车辆已认证或者尚未检测！");
					}
					return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！");
				}
				break;
			case "carSaleState":
				//上架状态 0 初始化 10 申请上架 20 上架 30 下架
				car.setCarSaleState(stateValue);
				car.setCarSaleTime(this.getDate(0));
				carLog.setCarLogInfo(ConstantState.getCarSaleStateMsg(stateValue));
				if(stateValue == ConstantState.CAR_SALE_STATE_INITIAL && StringUtils.isNotBlank(content)){
					carLog.setCarLogInfo("驳回上架申请：" + content);
					carLog.setCarStateValue(ConstantState.CAR_SALE_STATE_ONSALE_NG);
				}
				break;
			case "carStockState":
				car.setCarStockState(stateValue);
				car.setCarStockTime(this.getDate(0));
				carLog.setCarLogInfo(ConstantState.getCarStockStateMsg(stateValue));
				//库存状态
				if (stateValue == ConstantState.CAR_STOCK_STATE_OUT_ING && selectCar.getCarPledgeState() != null && selectCar.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED){
					return new ResultModel(ResultCode.RESULT_FAIL, "此车已抵押不能申请出库！");
				}else if (stateValue == ConstantState.CAR_STOCK_STATE_OUT_FINISH && selectCar.getCarPledgeState() != null && selectCar.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED){
					return new ResultModel(ResultCode.RESULT_FAIL, "此车已抵押不能出库！");
				}else if(stateValue == ConstantState.CAR_STOCK_STATE_OUT_FINISH){
					//出库，即下架
					car.setCarSaleTime(this.getDate(0));
					car.setCarSaleState(ConstantState.CAR_SALE_STATE_OFFSALE);
				}else if(stateValue == ConstantState.CAR_STOCK_STATE_IN_FINISH && selectCar.getCarStockState() == ConstantState.CAR_STOCK_STATE_IN_ING_ONSALE_ING ){
					// 如果为审核通过，切车辆目前状态为11 审核通过后，将状态上架状态置为已上架
					car.setCarSaleTime(this.getDate(0));
					car.setCarSaleState(ConstantState.CAR_SALE_STATE_ONSALE_FINISH);
				}else if(stateValue == ConstantState.CAR_STOCK_STATE_IN_FINISH && StringUtils.isNotBlank(content)){
					carLog.setCarLogInfo("驳回出库申请：" + content);
					carLog.setCarStateValue(ConstantState.CAR_STOCK_STATE_OUT_NG);
				}else if(stateValue == ConstantState.CAR_STOCK_STATE_IN_FINISH){
					//验证入库申请是否已经撤销
					Car carBack = new Car();
					carBack.setCarId(carInfo.getCarId());
					Car backCar = carRpcService.selectCar(carBack);
					if (backCar == null){
						return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID错误或此车不存在!");
					}
					if (backCar.getCarStockState() != null && backCar.getCarStockState() != ConstantState.CAR_STOCK_STATE_IN_ING){
						return new ResultModel(ResultCode.RESULT_FAIL, "该车辆入库申请状态已变更，审核失败!");
					}
				}else if(stateValue == ConstantState.CAR_STOCK_STATE_IN_NG){
					carLog.setCarLogInfo("驳回入库申请：" + content);
					carLog.setCarStateValue(ConstantState.CAR_STOCK_STATE_IN_NG);
				}
				break;
			case "carDetectState":
				// 检测状态 	500未初检  510初检不通过  520初检通过  530申请复检  540复检完成
				car.setCarDetectState(stateValue);
				carLog.setCarLogInfo(ConstantState.getCarDetectStateMsg(stateValue));
				if(stateValue == ConstantState.CAR_DETECT_STATE_FIRST_NG && StringUtils.isNotEmpty(content)){
					carLog.setCarLogInfo("初检不通过：" + content);
				}
				if(stateValue == ConstantState.CAR_DETECT_STATE_REDETECT_ING) {
					//申请复检
					//记录操作日志
					carLogs.add(carLog);
					car.setCarLogs(carLogs);
					if(StringUtils.isEmpty(carInfo.getMarketId())) {
						return new ResultModel(ResultCode.RESULT_FAIL, "市场Id不能为空！");
					}
					createDetection(carInfo, car);
					return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！");
				}
				
				break;
			case "carOrderState":
				// 预定状态
				car.setCarOrderState(stateValue);
				if(stateValue != ConstantState.CAR_ORDER_STATE_INITIAL){
					return new ResultModel(ResultCode.RESULT_FAIL, "预订状态错误！");
				}
				CarOrder carOrder = new CarOrder();
				carOrder.setCarId(car.getCarId());
				List<CarOrder> carOrders = carOrderRpcService.selectCarOrderList(carOrder);
				if(carOrders != null && carOrders.size() > 0){
					carOrder = new CarOrder();
					for(CarOrder order : carOrders){
						//删除预订信息
						carOrder.setOrderId(order.getOrderId());
						carOrderRpcService.deleteCarOrder(carOrder);
					}
				}
				carLog.setCarLogInfo("取消预订");
				break;
			case "carSiteState":
				//在场状态（400：未入场、410：已入场、420：出场审核中、430：出场审核通过、440：已出场）
				car.setCarSiteState(stateValue);
				car.setCarSiteTime(new Date());
				carLog.setCarLogInfo(ConstantState.getCarSiteStateMsg(stateValue));
				if(stateValue == ConstantState.CAR_SITE_STATE_IN_FINISH && StringUtils.isNotBlank(content)){
					carLog.setCarLogInfo("驳回临时出场申请：" + content);
					carLog.setCarStateValue(ConstantState.CAR_SITE_STATE_OUT_NG);
				}
				break;
			default:
				return new ResultModel(ResultCode.RESULT_FAIL, "状态KEY错误！");
		}
		//记录操作日志
		carLogs.add(carLog);
		car.setCarLogs(carLogs);
		carRpcService.updateCarState (car);

		CarStateMsg carStateMsg = new CarStateMsg();
		carStateMsg.setCarId(selectCar.getCarId());
		carStateMsg.setCarVin(selectCar.getCarVin());
		carStateMsg.setCarTitle(selectCar.getCarTitle());
		carStateMsg.setShopId(selectCar.getShopId());
		carStateMsg.setCheckTime(new Date());
		carStateMsg.setContent(content);
//		// 上架状态
		if(car.getCarSaleState() != null){
			if(car.getCarSaleState() == ConstantState.CAR_SALE_STATE_INITIAL && StringUtils.isNotEmpty(content)){
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_SALE_STATE_0, carStateMsg, "车辆上架申请驳回");
			}else if(stateValue == ConstantState.CAR_SALE_STATE_ONSALE_FINISH){
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_SALE_STATE_20, car, "车辆上架");
			}else if(stateValue == ConstantState.CAR_SALE_STATE_OFFSALE){
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_SALE_STATE_30, car, "车辆下架");
			}
		}
		// 库存状态
		if(car.getCarStockState() != null){
			if(car.getCarStockState() == ConstantState.CAR_STOCK_STATE_OUT_FINISH){
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_STOCK_STATE_40, car, "车辆出库");
			}else if(car.getCarStockState() == ConstantState.CAR_STOCK_STATE_IN_FINISH && StringUtils.isEmpty(content)){
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_STOCK_STATE_20, carStateMsg, "车辆入库");
			}else if(car.getCarStockState() == ConstantState.CAR_STOCK_STATE_IN_NG){
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_STOCK_STATE_0, carStateMsg, "车辆入库申请驳回");
			}
		}
		// 在场状态
		if(car.getCarSiteState() != null){
			if(car.getCarSiteState() == ConstantState.CAR_SITE_STATE_IN_FINISH && StringUtils.isNotEmpty(content)){ // 临时出场审核不通过
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_SITE_STATE_410, carStateMsg, "车辆出场申请驳回");
			}else if(car.getCarSiteState() == ConstantState.CAR_SITE_STATE_OUT_PASS){ // 临时出场审核通过
				produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_SITE_STATE_430, carStateMsg, "车辆出场申请通过");
			}
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！", car);
	}

	private void createDetection(Car carInfo, Car car) {
		//初始化检测单信息
		Detection detection = new Detection();
		detection.setCar(car);//车辆信息
		detection.setCarId(carInfo.getCarId());
		detection.setMarketId(carInfo.getMarketId());
		detection.setCreateUserId(carInfo.getUserId());
		detection.setDetectionState(ConstantState.DETECTION_STATE_INITIAL);//检测状态 0 发起 10 已派单 20 已检测 30 总部审核
		Date cDate = new Date();
		detection.setDetectionCreateTime(cDate);
		detection.setDetectionUpdateTime(cDate);
		detection.setDetectionPrice(new BigDecimal(0));
		detectionRpcService.insertDetection(detection);
	}

	private boolean createCarAuth(Car carInfo,Car car, Car selectCar) {
		if(selectCar.getCarAuthState() == ConstantState.CAR_AUTH_STATE_AUTHED){
			// 车辆已认证
			return false;
		}
		if(selectCar.getCarDetectState() != ConstantState.CAR_DETECT_STATE_REDETECT_FINISH){// 复检未完成
			// 车辆尚未复检，无法认证
			return false;
		}
		Detection detectionTemp = new Detection();
		detectionTemp.setCarId(carInfo.getCarId());
		detectionTemp = detectionRpcService.selectDetection(detectionTemp);
		if(detectionTemp == null || detectionTemp.getDetectionState() < ConstantState.DETECTION_STATE_DETECTED){
			// 车辆尚未检测，无法认证
			return false;
		}
		CarAuth carAuth = new CarAuth();
		carAuth.setCarId(carInfo.getCarId());
		if(carAuthRpcService.selectCarAuth(carAuth) != null){
			// 车辆已认证
			return false;
		}
		//创建车辆认证信息
		carAuth.setCar(car);
		carAuth.setCreateUserId(carInfo.getUserId());
		carAuthRpcService.insertCarAuth(carAuth);
		return true;
	}
	
	private void produceRocketMqMessage(String topic, String tag, Object obj, String msg){
		try {
			rocketMqProducer.produceMessage(topic, tag, obj);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(msg + "异常", e);
		}
	}
	/**
	 * 绑定RFID
	 * @param carRfid
	 * @param carId
	 * @return
	 */
	@RequestMapping(value = "/car/bindCarRfid", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel bindCarRfid(String carRfid, String carId, String userId, HttpServletRequest request) {
		String source = request.getHeader("source");
		if(StringUtils.isEmpty(carId)){
			return new ResultModel(ResultCode.RESULT_FAIL, "carId不能为空！");
		}
		if(StringUtils.isEmpty(carRfid)){
			return new ResultModel(ResultCode.RESULT_FAIL, "RFID不能为空！");
		}
		if(StringUtils.isEmpty(userId)){
			return new ResultModel(ResultCode.RESULT_FAIL, "userId不能为空！");
		}
		Date cDate = new Date();
		Car car = new Car();
		car.setCarRfid(carRfid);
		Car selectCar = carRpcService.selectCar(car);
		if(selectCar != null && !selectCar.getCarId().equals(carId)){
			return new ResultModel(ResultCode.RESULT_FAIL, "RFID不能重复绑定！");
		}
		car.setCarId(carId);
		car.setCarRfidTime(cDate);
		car.setCarUpdateTime(cDate);
//		car.setMarketId(marketId);
		CarLog carLog = new CarLog(cDate, userId, carId);
		carLog.setCarLogInfo("绑定rfid：RFID=" + carRfid);
		carLog.setCarStateKey("carRfidState");
		carLog.setCarStateValue(ConstantState.CAR_RFID_STATE_BINDED);
		carLog.setCarLogSource(source);
		List<CarLog> carLogs = new ArrayList<>();
		carLogs.add(carLog);
		car.setCarLogs(carLogs);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "绑定成功！", carRpcService.updateCarBindRfid(car, null));
	}

	/**
	 * 根据订阅信息查询订阅车辆列表
	 *
	 * @param car
	 * @return
	 */
	@RequestMapping(value = {"/car/getCarListByCarSelectTemplate"}, method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel selectCarListByCarSelectTemplate(Car car){
		if (car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "订阅信息不能为空！");
		}
		if (StringUtils.isEmpty(car.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if (StringUtils.isEmpty(car.getShopId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商铺ID不能为空！");
		}
		CarSelectTemplate carSelectTemplate = new CarSelectTemplate();
		carSelectTemplate.setMarketId(car.getMarketId());
		carSelectTemplate.setShopId(car.getShopId());
		car.setMarketId(null);
		car.setShopId(null);
		//根据订阅条件查询订阅信息列表
		List<CarSelectTemplate> carSelectTemplateList = carSelectTemplateRpcService.selectCarSelectTemplateListByGroup(carSelectTemplate);
		//再根据订阅列表查找车辆信息列表
		if(carSelectTemplateList == null || carSelectTemplateList.size() == 0){
			return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", new ArrayList<>());
		}else{
			return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", carRpcService.selectCarListByCarSelectTemplateList(car, carSelectTemplateList));
		}

	}

	/**
	 * 判断指定图片是否为空方法
	 * @param images
	 * @param imageKey
	 * @return
	 */
	private boolean valiCarImageKey(List<CarImage> images, String imageKey){
		for(CarImage cImage : images) {
			if(cImage.getImageKey().equalsIgnoreCase(imageKey) && StringUtils.isNotEmpty(cImage.getImageUrl())){
				return true;
			}
		}
		return false;
	}

	/**
	 * 修改车辆抵押状态
	 * @param car
	 * @param stateValue
	 * @param carImageJson
	 * @return
	 */
	@RequestMapping(value = "/car/setPledge", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel setPledge(Car car, Integer stateValue, String carImageJson, HttpServletRequest request) {
		String source = request.getHeader("source");
		if(car == null || StringUtils.isEmpty(car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(StringUtils.isEmpty(car.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "操作人ID不能为空！");
		}
		if(stateValue == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "状态值不能为空！");
		}
		if(stateValue != ConstantState.CAR_PLEDG_STATE_INITIAL && stateValue != ConstantState.CAR_PLEDG_STATE_PLEDGED) {
			return new ResultModel(ResultCode.RESULT_FAIL, "状态值不正确！");
		}
		Car selectCar1 = new Car();
		selectCar1.setCarId(car.getCarId());
		Car selectCar = carRpcService.selectCar(selectCar1);
		CarLog carLog = new CarLog(new Date(), car.getUserId(), car.getCarId());
		carLog.setCarStateKey("carPledgeState");
		carLog.setCarStateValue(stateValue);
		carLog.setCarLogSource(source);
		List<CarLog> carLogs = new ArrayList<>();
		if (stateValue == ConstantState.CAR_PLEDG_STATE_PLEDGED) {
			// 车辆抵押
			if (StringUtils.isEmpty(selectCar.getCarRfid())) {
				return new ResultModel(ResultCode.RESULT_FAIL, "RFID未绑定!");
			}
			if (selectCar.getCarStockState() != null && selectCar.getCarStockState() != ConstantState.CAR_STOCK_STATE_IN_FINISH) {
				return new ResultModel(ResultCode.RESULT_FAIL, "车辆未入库，暂不能办理抵押!");
			}
			if (selectCar.getCarSiteState() != null && selectCar.getCarSiteState() != ConstantState.CAR_SITE_STATE_IN_FINISH) {
				return new ResultModel(ResultCode.RESULT_FAIL, "车辆不在场或已申请抵押业务，暂不能办理抵押!");
			}
			if (StringUtils.isEmpty(carImageJson)){
				return new ResultModel(ResultCode.RESULT_FAIL, "图片参数不能为空！");
			}
			List<CarImage> images1 = JSON.parseArray(carImageJson, CarImage.class);
			//过滤空的图片url
			List<CarImage> images = new ArrayList<>();
			for (CarImage carImage:images1) {
				if (StringUtils.isNotEmpty(carImage.getImageUrl())){
					images.add(carImage);
				}
			}
			if(images.size() == 0){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传抵押图片！");
			}
			if (!valiCarImageKey(images, "pledge_vehicle_license")){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传您的行驶证！");
			}
			if (!valiCarImageKey(images, "pledge_registration_license")){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传您的登记证！");
			}
			if (!valiCarImageKey(images, "pledge_keys")){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传您的车钥匙照片！");
			}
			if (!valiCarImageKey(images, "pledge_duty_paid")){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传您的完税凭证照片！");
			}
			if (!valiCarImageKey(images, "pledge_insurance")){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传您的保单照片！");
			}
			if (!valiCarImageKey(images, "pledge_invoice")){
				return new ResultModel(ResultCode.RESULT_FAIL, "请上传您的发票照片！");
			}
			selectCar.setCarImages(images);
			carLog.setCarLogInfo((stateValue == ConstantState.CAR_PLEDG_STATE_PLEDGED ? "抵押" : "未知"));
		} else {
			//如果车辆还未出场，解压时将出场状态重置为在场状态
			if(selectCar.getCarSiteState() != null && selectCar.getCarSiteState() != ConstantState.CAR_SITE_STATE_OUT_FINISH){
				selectCar.setCarSiteState(ConstantState.CAR_SITE_STATE_IN_FINISH);
				selectCar.setCarSiteTime(new Date());
			}
			carLog.setCarLogInfo((stateValue == ConstantState.CAR_PLEDG_STATE_INITIAL ? "未抵押" : "未知"));
		}
		selectCar.setCarPledgeState(stateValue);
		carLogs.add(carLog);
		selectCar.setCarLogs(carLogs);
		carRpcService.updateCarOfPledge(selectCar);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！", selectCar);
	}
	/**
	 * 删除未入库车辆
	 * @param car
	 * @return
	 */
	@RequestMapping(value = "/car/deleteCar", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel deleteCar(Car car,HttpServletRequest request) {
		String source = request.getHeader("source");
		if(car == null || StringUtils.isEmpty(car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(StringUtils.isEmpty(car.getUserId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "操作人ID不能为空！");
		}
		Car selectCar = carRpcService.selectCar(new Car(car.getCarId()));
		if(selectCar == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不正确！");
		}
		if(selectCar.getCarStockState() >= ConstantState.CAR_STOCK_STATE_IN_ING){ // 车辆库存状态>=10
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆不是未入库状态！");
		}
		//记录日志信息
		CarLog carLog = new CarLog("删除未入库车辆信息", new Date(), car.getUserId(), car.getCarId());
		carLog.setCarStateKey("carlsDelete");
		carLog.setCarStateValue(1);
		carLog.setCarLogSource(source);
		List<CarLog> carLogs = new ArrayList<>();
		carLogs.add(carLog);
		selectCar.setCarLogs(carLogs);
		carRpcService.deleteCar(selectCar);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "删除成功！");
	 }
	
	/**
	 * 查询车辆初检测列表信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/car/getCarFirstDetectList", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getCarFirstDetectList(Car car) {
		if(StringUtils.isEmpty(car.getMarketId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "marketId不能为空！");
		}
		// 添加排序方式，先按检测状态，再按创建时间倒序
		car.setOrderColunm("CAR_DETECT_STATE ,CAR_CREATE_TIME DESC ");
		List<Car> cars = carRpcService.selectCarList(car);
		if(cars != null && !cars.isEmpty()){
			for (Car carInfo : cars){
				if(carInfo.getCarPledgeState() != null && carInfo.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED
						&& carInfo.getCarSiteState() != null && carInfo.getCarSiteState() == ConstantState.CAR_SITE_STATE_OUT_FINISH){
					if(carInfo.getCarSiteTime() != null) {
						if ((System.currentTimeMillis() - carInfo.getCarSiteTime().getTime()) / (1000 * 60) > 300) {
							carInfo.setCarSiteStatus(1);
						}
					}
				}
			}
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", cars);
	}
}
